package com.lyh.system.biz.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyh.common.core.domain.AjaxResult;
import com.lyh.common.core.domain.BaseEntity;
import com.lyh.common.core.domain.entity.SysUser;
import com.lyh.common.enums.PaymentMethodEnum;
import com.lyh.common.enums.StoreOrderStatusEnum;
import com.lyh.common.utils.StringUtils;
import com.lyh.system.biz.IOrderBiz;
import com.lyh.system.domain.MemberPurchaseInfo;
import com.lyh.system.domain.Order;
import com.lyh.system.domain.req.UserIncomePageReq;
import com.lyh.system.domain.resp.UserIncomeResp;
import com.lyh.system.mapper.MemberPurchaseInfoMapper;
import com.lyh.system.mapper.OrderMapper;
import com.lyh.system.mapper.SysUserMapper;
import com.lyh.system.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class IOrderBizImpl implements IOrderBiz {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberPurchaseInfoMapper  purchaseInfoMapper;
    @Override
    public void orderRebate(Order order, SysUser sysUser) {
        for (int i = 0; i < order.getGoodsNum(); i++) {
            goodsService.purchase(order.getGoodsId(), order.getId(), sysUser);
        }
    }

    @Override
    public List<UserIncomeResp> orderByUser(UserIncomePageReq req) {
        List<UserIncomeResp> sysUsers = sysUserMapper.getUserByMembers(req);
        //查询对应所有订单
        List<Long> userList = sysUsers.stream().map(UserIncomeResp::getUserId).collect(Collectors.toList());
        List<Order> orders = orderMapper.selectList(new LambdaQueryWrapper<Order>()
                .in(Order::getUserId, userList)
                .in(Order::getGoodsId,1,2)
                .ne(Order::getStatus, StoreOrderStatusEnum.wait_pay.name()));
        //查找预约单数
        List<MemberPurchaseInfo> memberPurchaseInfos = purchaseInfoMapper.selectList(new LambdaQueryWrapper<MemberPurchaseInfo>()
                .in(MemberPurchaseInfo::getUserId, userList));
        //按userId分组
        Map<Long, List<MemberPurchaseInfo>> purchaseMap = memberPurchaseInfos.stream().collect(Collectors.groupingBy(MemberPurchaseInfo::getUserId));


        if(sysUsers!=null && sysUsers.size()>0){
            Map<Long, List<Order>> collect = orders.stream().collect(Collectors.groupingBy(Order::getUserId));
             sysUsers.stream().forEach(resp -> {
                if(resp.getUserId().equals(Long.valueOf(req.getUserId()))){
                    resp.setPersonTypeName("本人");
                    resp.setPersonType(1);
                }else if(req.getRealList().contains(resp.getUserId())){
                    resp.setPersonTypeName("直推");
                    resp.setPersonType(2);

                }else{
                    resp.setPersonTypeName("间推");
                    resp.setPersonType(3);
                }

                if(orders!=null && orders.size()>0){
                    List<Order> orders1 = collect.get(resp.getUserId());
                    //按产品分组
                    if (orders1 != null && orders1.size() > 0) {
                        Map<Long, List<Order>> orderUsers = orders1.stream().collect(Collectors.groupingBy(Order::getGoodsId));
                        List<Order> ordersOnline = orderUsers.get(1l);
                        List<Order> ordersStore = orderUsers.get(2l);
                        resp.setOnlineNum(ordersOnline == null ? 0 : ordersOnline.size());
                        resp.setStoreNum(ordersStore == null ? 0 : ordersStore.size());
                        List<Order> collect1 = orders1.stream().sorted(Comparator.comparing(Order::getGoodsId)).collect(Collectors.toList());
                        collect1.stream().forEach(item -> {
                            item.setGoodClassName(item.getGoodsId() == 1 ? "线上" : "门店");
                            item.setPaymentMethodName(PaymentMethodEnum.valueOf(item.getPaymentMethod()).getTitle());
                        });

                        resp.setItem(collect1);

                        List<MemberPurchaseInfo> purchaseInfos = purchaseMap.get(resp.getUserId());
                        if(purchaseInfos!=null && purchaseInfos.size()>0){
                            resp.setPurchaseNum(purchaseInfos.size());
                            BigDecimal assetEvidenceNum = purchaseInfos.stream().map(MemberPurchaseInfo::getAssetEvidenceNum).reduce(BigDecimal.ZERO, BigDecimal::add);
                            resp.setPurchaseMoney(assetEvidenceNum);
                        }
                    }
                }
            });
            return sysUsers;
        }

        return null;
    }


    //取字典

    @Override
    public AjaxResult getUserOrderRep(String userId) {
        //直推用户数
        Map<String, Object> map = new HashMap<>();
        map.put("zNum",0);//直推人数
        map.put("jNum",0);//间推人数
        map.put("storeOrderNums",0);//门店订单数
        map.put("onlineOrderNums",0);//线上订单数
        map.put("storeOrderAmount",0);//门店金额
        map.put("onlineOrderAmount",0);//线上订单数
        map.put("prurchaseNum",0);//预约总单数
        map.put("prurchaseMoney",0);//预约总金额
        map.put("orderMoney",0);//预约总金额
        map.put("yqPerson","");//邀请人
        List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getParentId, userId)
                .orderByAsc(BaseEntity::getCreateTime));
        if(sysUsers!=null && sysUsers.size()>0){
            int zNum = sysUsers.size();
            map.put("zNum",zNum);//直推人数
        }else{
            return AjaxResult.success(map);
        }
        List<String> userList = sysUsers.stream().map(c->c.getUserId().toString()).collect(Collectors.toList());

        //间推用户树
        SysUser sysUser = sysUserMapper.selectById(userId);
        //查找父级用户id
        if(sysUser!=null && sysUser.getParentId()!=null){
            SysUser sysUserParent = sysUserMapper.selectById(sysUser.getParentId());
            map.put("yqPerson",sysUserParent.getMemberId());//邀请人
        }else{
            map.put("yqPerson","无");//邀请人
        }

        String indirectInviteCodes = sysUser.getIndirectInviteCodes();
        if(StringUtils.isNotEmpty(indirectInviteCodes)){
            //间推
            List<String> memberIds = Arrays.asList(indirectInviteCodes.split(","));
            //间推人数
            int jNum = memberIds.size();
            map.put("jNum",jNum);//间推人数
            UserIncomePageReq userIncomePageReq = new UserIncomePageReq();
            userIncomePageReq.setList(memberIds);

            List<SysUser> userByMemberId = sysUserMapper.getUserByMemberId(userIncomePageReq);
            userList.addAll(userByMemberId.stream().map(c->c.getUserId().toString()).collect(Collectors.toList()));


        }
        userList.add(userId);
        //门店订单总数
        List<Order> storeOrders = orderMapper.selectList(new LambdaQueryWrapper<Order>()
                .in(Order::getUserId,userList)
                .in(Order::getGoodsId,2)
                .ne(Order::getStatus, StoreOrderStatusEnum.wait_pay.name()));

        //线上订单总数
        List<Order> onlineOrders = orderMapper.selectList(new LambdaQueryWrapper<Order>()
                .in(Order::getUserId,userList)
                .in(Order::getGoodsId,1)
                .ne(Order::getStatus, StoreOrderStatusEnum.wait_pay.name()));
        int storeOrderNums = storeOrders.size();
        int onlineOrderNums = onlineOrders.size();

        map.put("storeOrderNums",storeOrderNums);//门店订单数
        map.put("onlineOrderNums",onlineOrderNums);//线上订单数

        BigDecimal storeOrderAmount = storeOrders.stream().map(Order::getActualPayment).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal onlineOrderAmount = onlineOrders.stream().map(Order::getActualPayment).reduce(BigDecimal.ZERO, BigDecimal::add);

        if(storeOrderAmount!=null){
            map.put("storeOrderAmount",storeOrderAmount);//门店金额
        }
        if(onlineOrderAmount!=null){
            map.put("onlineOrderAmount",onlineOrderAmount);//门店金额
        }

        //订单总额
        List<Order> storeOrderAlls = orderMapper.selectList(new LambdaQueryWrapper<Order>()
                .in(Order::getUserId,userList)
                .ne(Order::getStatus, StoreOrderStatusEnum.wait_pay.name()));
            BigDecimal actualPayment = storeOrderAlls.stream().map(Order::getActualPayment).reduce(BigDecimal.ZERO, BigDecimal::add);
            map.put("orderMoney",actualPayment);//线上订单数


            //团队预约单数
        List<MemberPurchaseInfo> memberPurchaseInfos = purchaseInfoMapper.selectList(new LambdaQueryWrapper<MemberPurchaseInfo>()
                .in(MemberPurchaseInfo::getUserId, userList));
        if(memberPurchaseInfos!=null && memberPurchaseInfos.size()>0){
            map.put("prurchaseNum",memberPurchaseInfos.size());
            BigDecimal assetEvidenceNum = memberPurchaseInfos.stream().map(MemberPurchaseInfo::getAssetEvidenceNum).reduce(BigDecimal.ZERO, BigDecimal::add);
            map.put("prurchaseMoney",assetEvidenceNum);

        }
        return AjaxResult.success(map);
    }
}
